#include <unistd.h>
#include "comm.hpp"

class Init
{
public:
    Init()
    {
        key_t key = GetKey();
        std::cout << "key:" << ToHex(key) << std::endl;
        sleep(5);
        bool ret = MakeFifo();
        if(!ret)
            return;
        shmid = CreatShm(key);
        std::cout << "shmid:" << shmid << std::endl;
        std::cout << "开始将shm映射到进程的地址空间中" << std::endl;
        s = (char*)shmat(shmid, nullptr, 0);
        fd = open(filename.c_str(), O_RDONLY);
    }
public:
    int shmid;
    int fd;
    char *s;
};
int main()
{
    Init init;

    while(true)
    {
        int code = 0;
        int n = read(init.fd, &code , sizeof(int));
        if(n > 0)
        {
            std::cout << "共享内存中的内容为" << init.s << std::endl;
        }
        else if(init.s == 0)
        {
            break;
        }
    }
    std::cout << "将shm再进程的地址空间中的映射移除" <<std::endl;
    shmdt(init.s);
    shmctl(init.shmid, IPC_RMID, nullptr);
    unlink(filename.c_str());
    sleep(5);

    return 0;
}